//
//  UITabbarViewController-redPoint.swift
//  HHBaseModule
//
//  Created by renxibin on 2021/8/26.
//

import Foundation
public extension UITabBar {
    /// 显示消息红点
    /// - Parameters:
    ///   - index: index
    ///   - showState: 是否显示红点
    func showBadgeOnItemWithoutNum(index:Int, showState:Bool) {
        removeBadgeOnItem(index: index)
        if !showState {
            return
        }
        let bview = UIView.init()
        bview.tag = 600+index
        bview.layer.cornerRadius = 4
        bview.clipsToBounds = true
        bview.backgroundColor = UIColor.red
        let tabFrame = self.frame
        
        let percentX = (Float(index)+0.55) / 3.0//(tabBar的总个数)
        let x = CGFloat(ceilf(percentX*Float(tabFrame.width)))
        let y = CGFloat(ceilf(0.15*Float(tabFrame.height)))
        bview.frame = CGRect(x: x, y: y, width: 8, height: 8)

        addSubview(bview)
        bringSubviewToFront(bview)
    }
    
    func showBadgeStrOnItem(index:Int, title:String) {
         
    }
    /// 设置消息红点 带消息数
    /// - Parameters:
    ///   - index: index
    ///   - count: 消息数 超过99 显示99+
    func showBadgeOnItem(index:Int, count:Int) {

        removeBadgeOnItem(index: index)
        let bview = UIView.init()
        bview.tag = 888+index
        bview.layer.cornerRadius = 9
        bview.clipsToBounds = true
        bview.backgroundColor = UIColor.red
        let tabFrame = self.frame
        
        let percentX = (Float(index)+0.6) / 3.0//(tabBar的总个数)
        let x = CGFloat(ceilf(percentX*Float(tabFrame.width)))
        let y = CGFloat(ceilf(0.1*Float(tabFrame.height)))
        bview.frame = CGRect(x: x, y: y, width: 18, height: 18)
        
        let cLabel = UILabel.init()
        cLabel.text = "\(count)"
        if count > 99 {
            cLabel.text = "99+"
        }
        cLabel.frame = CGRect(x: 0, y: 0, width: 18, height: 18)
        cLabel.font = UIFont.systemFont(ofSize: 10)
        cLabel.textColor = UIColor.white
        cLabel.textAlignment = .center
        bview.addSubview(cLabel)
        
        addSubview(bview)
        bringSubviewToFront(bview)
    }

        
    // 隐藏红点
    func hideBadgeOnItem(index:Int) {

        removeBadgeOnItem(index: index)
    }
    // 移除控件
    func removeBadgeOnItem(index:Int) {

        for subView:UIView in subviews {
            if subView.tag == 888+index {
                subView.removeFromSuperview()
            }
            if subView.tag == 600+index {
                subView.removeFromSuperview()
            }
        }
    }
}
